﻿using AntdUI;
using CKS.PLC.Core.Cache;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Dto.Business.ProductionControl;
using ZR.Model.Models.ProductionControl;

namespace CKS.MES.Server.Controllers.Business.ProductionControl
{
    [AllowAnonymous]
    [Route("api/packagingtask")]
    public class PackagingTaskController : BaseController
    {



        [HttpPost("receive")]
        [AllowAnonymous]
        public IActionResult ReceiveTask([FromBody]PackagingTaskReceiveDto parm)
        {
            //校验容器号是否已经被使用，未使用的容器可以进行绑定任务
            // InternalApp.Fsql

            var container = fsql.Select<CksContainer>().Where(a => a.ContainerNo == parm.ContainerNo && a.ProductMode == 1).First();
            if (container == null)
            {
                container = new CksContainer()
                {
                    ContainerNo = parm.ContainerNo,
                    CreatedTime = DateTime.Now,
                    Status = 0,
                    TaskNo = string.Empty,
                    ProductMode = 1,
                };
                container.Id = fsql.Insert<CksContainer>(container).ExecuteIdentity();
            }
            Dictionary<string, string> response = new Dictionary<string, string>();
            if (container.Status > 0)
            {
                response["SubCode"] = "1";
                response["Message"] = "容器号已被占用";
                return SUCCESS(new
                {
                    data = response
                });
            }



            //生成任务号
            CksPackagingTask packagingTask = GenerateTask(parm, container);

            response["SubCode"] = "0";
            response["Message"] = "ok";
            response["TaskNo"] = container.TaskNo;
            response["OrderNo"] = packagingTask.OrderNo;
            response["PackageNo"] = packagingTask.PackageNo;
            response["WaybillNo"] = packagingTask.WaybillNo;
            return SUCCESS(new
            {
                data = response
            });

        }

        [HttpPost("rebind")]
        [AllowAnonymous]
        public IActionResult ReBind([FromBody] PackagingTaskReceiveDto parm)
        {
            //校验容器号是否已经被使用，未使用的容器可以进行绑定任务
            // InternalApp.Fsql
            string newContainerNo = GetRetStr(parm.ContainerNo);
            if(newContainerNo.IsEmpty())
            {
                //输入错误
                return ToResponse(ResultCode.FAIL, "输入错误");
            }
           var task = fsql.Select<CksPackagingTask>().Where(a => a.TaskNo == parm.TaskNo).First();
            var container = fsql.Select<CksContainer>().Where(a => a.ContainerNo == task.ContainerNo &&
                                a.ProductMode == task.ProductMode).First();
            var newcontainer = fsql.Select<CksContainer>().Where(a => a.ContainerNo == newContainerNo &&
                                a.ProductMode == task.ProductMode).First();
            if(newcontainer?.Status == 1)
            {
                return ToResponse(ResultCode.FAIL, "您输入的容器已被使用");
            }
            if(container.TaskNo == task.TaskNo )
            {
                //修改旧容器为释放状态
                container.Status = 0;
                container.TaskNo = string.Empty;
                fsql.Update<CksContainer>().SetSource(container).ExecuteAffrows();
            }


            if(newcontainer == null)
            {
                //新增容器
                newcontainer = new CksContainer() {
                    ContainerNo = newContainerNo,
                    CreatedTime = DateTime.Now,
                    Status = 0,
                    ProductMode = task.ProductMode,
                    TaskNo = task.TaskNo,
                };
                newcontainer.Id = fsql.Insert<CksContainer>(newcontainer).ExecuteIdentity();
            }
            
            newcontainer.TaskNo = task.TaskNo;
            newcontainer.Status = 1;
            fsql.Update<CksContainer>().SetSource(newcontainer).ExecuteAffrows();

            //修改任务
            task.ContainerNo = newContainerNo;
            task.Position = "上料流水线";
            task.TaskStatus = TaskStatusType.重新绑定箱号;
            fsql.Update<CksPackagingTask>().SetSource(task).ExecuteAffrows();


            return OK();

        }

        [HttpPost("deletetask")]
        [AllowAnonymous]
        public IActionResult DeleteTask([FromBody] PackagingTaskReceiveDto parm)
        {
            var taskItem = fsql.Select<CksPackagingTask>().Where(a => a.TaskNo == parm.TaskNo).First();
            if(taskItem!=null)
            {
                //查询托盘\解绑托盘\删除任务
                var container =fsql.Select<CksContainer>().Where(a => a.TaskNo == parm.TaskNo).First();
                if(container!=null && container.Status == 1)
                {
                    container.Status = 0;
                    fsql.Update<CksContainer>().SetSource(container).ExecuteAffrows();
                }
                fsql.Delete<CksPackagingTask>().Where(a => a.TaskNo == parm.TaskNo).ExecuteAffrows();

            }
            return OK();
        }

        //unbind
        [HttpPost("unbind")]
        [AllowAnonymous]
        public IActionResult UnBind([FromBody] PackagingTaskReceiveDto parm)
        {
            var taskItem = fsql.Select<CksPackagingTask>().Where(a => a.TaskNo == parm.TaskNo).First();
            if (taskItem != null)
            {
                //查询托盘\解绑托盘\删除任务
                var container = fsql.Select<CksContainer>().Where(a => a.TaskNo == parm.TaskNo).First();
                if (container != null && container.Status == 1)
                {
                    container.Status = 0;
                    fsql.Update<CksContainer>().SetSource(container).ExecuteAffrows();
                }
                taskItem.ContainerNo = "";
                taskItem.TaskStatus = TaskStatusType.解除容器绑定_手动;
                fsql.Update<CksPackagingTask>().SetSource(taskItem).ExecuteAffrows();
                

            }
            return OK();
        }


        private string GetRetStr(string input)
        {
            if (input.IsEmpty()) return string.Empty;
            if (input.ToUpper().StartsWith("AP"))
            {
                var numStr = input.Substring(2);
                return "AP" + Convert.ToInt32(numStr).ToString("000");
            }
            else
            {
                return "AP" + Convert.ToInt32(input).ToString("000");
            }
        }

        private static CksPackagingTask GenerateTask(PackagingTaskReceiveDto parm, CksContainer container)
        {
            string dayCacheKey = $"T{DateTime.Now.ToString("yyMMdd")}";
            var nextSeriaNumber = ServiceCommon.GetNextSerialNumber(dayCacheKey);
            container.TaskNo = $"{dayCacheKey}{nextSeriaNumber.ToString().PadLeft(4, '0')}";
            container.Status = 1;
            container.WaybillNo = parm.WaybillNo;
            fsql.Update<CksContainer>().SetSource(container).ExecuteAffrows();
            //生成任务记录
            CksPackagingTask packagingTask = new CksPackagingTask()
            {
                ContainerNo = parm.ContainerNo,
                CreatedTime = DateTime.Now,
                OrderNo = parm.OrderNo,
                PackageNo = parm.PackageNo,
                Position = "投料口",
                TaskStatus = TaskStatusType.接收订单信息,
                TaskNo = container.TaskNo,
                WaybillNo = parm.WaybillNo,
                ProductMode = 1
            };
            fsql.Insert(packagingTask).ExecuteAffrows();
            return packagingTask;
        }
    }
}
